package tree.reader;

import java.awt.image.BufferedImage;
import java.io.IOException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;

import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import tree.model.Node;
import tree.person.Person;
import tree.utils.ImageReader;

public class QueryXML {
	
	public Node<Person> query(long id) throws ParserConfigurationException, SAXException,
			IOException, XPathExpressionException {
		// Standard of reading a XML file
		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
		factory.setNamespaceAware(true);
		DocumentBuilder builder;
		Document doc = null;
		XPathExpression expr = null;
		builder = factory.newDocumentBuilder();
		doc = builder.parse("tree.xml");

		// Create a XPathFactory
		XPathFactory xFactory = XPathFactory.newInstance();

		// Create a XPath object
		XPath xpath = xFactory.newXPath();

		// Compile the XPath expression
		expr = xpath.compile("//tree.person.Person[id="+id+"]/*/text()");
		// Run the query and get a nodeset
		Object result = expr.evaluate(doc, XPathConstants.NODESET);
		
		
		
		// Cast the result to a DOM NodeList
		NodeList nodes = (NodeList) result;
		
		long nId = Long.parseLong(nodes.item(0).getNodeValue());
		long mumId = Long.parseLong(nodes.item(1).getNodeValue());
		long dadId = Long.parseLong(nodes.item(2).getNodeValue());
		String name = nodes.item(3).getNodeValue();
		String surname = nodes.item(4).getNodeValue();
		String sex = nodes.item(5).getNodeValue();
		String foto = nodes.item(6).getNodeValue();
		
		BufferedImage img = ImageReader.readImage(foto);
		Person person = new Person(nId, mumId, dadId, name, surname, sex, foto);
		person.setImage(img);
		
		
		Node<Person> node = new Node<Person>(id);
		node.setData(person);
		
		return node;
		
	}

}